<template>
	<div class="page">
		<el-card class="box-card">
			<div slot="header" class="clearfix">
			    <span class="card-title">{{cardInfo.STICKETNAMECH}}</span>
			    <span class="timeOut" v-if="$route.query.OVERTIME !== '未超时'">超时{{$route.query.OVERTIME}}分钟（{{computedTime($route.query.OVERTIME)}}）</span>
			</div>
			<div class="head-text">入园时长：{{$route.query.STAYTIME}}</div>
			<div class="head-text">手机号：{{cardInfo.MOBILE}}</div>
			<div class="head-text">升级时长：{{orderInfo.UPGRADETIME}}</div>
		</el-card>
		<div class="wxPay card" @click="SelectPayType('wx')" v-if="isWechat">
			<div class="left">
				<img src="../../assets/weixin.png" width="25" height="25">
				<span class="leftText">微信支付</span>
			</div>
			<div class="rigth">
				<img :src="PayType == 'wx' ? select : Noselect" width="18" height="18">
			</div>
		</div>
		<div class="zfbPay card" @click="SelectPayType('zfb')" v-if="isAlipay">
			<div class="left">
				<img src="../../assets/zhifubao.png" width="25" height="25">
				<span class="leftText">支付宝支付</span>
			</div>
			<div class="rigth">
				<img :src="PayType == 'zfb' ? select : Noselect" width="18" height="18">
			</div>
		</div>
		<div class="waitPay">
			<div class="content">
				<span class="text">待支付：</span>
				<span class="price">{{orderInfo.AMOUNT}} 元</span>
			</div>
		</div>
		<div class="btn-list">
			<el-button class="detail-Info" @click="back">返回</el-button>
			<el-button class="pay" @click="Pay">立即支付</el-button>
		</div>
	</div>
</template>

<script>
	import { mapMutations,mapGetters } from "vuex";
	export default {
		data () {
			return {
				sum : 0,
				PayType : "wx",
				orderInfo : {},
				cardInfo : {},
				select : require("../../assets/gouxuan.png"),
				Noselect : require("../../assets/buxuan.png"),
				Code : "",
				isWechat : false,
				isAlipay : false,
				query : {}
			}
		},
		created () {
			this.cardInfo = JSON.parse(sessionStorage.getItem("cardDetailInfo"));
			console.log(this.$route.query)
			this.getCode();
			this.AlipayOrWxPay();
		},
		methods : {
			computedTime (time) {
				if (time) {
					let num = time / 60;
					num = num.toFixed(1);
					return num + "小时"
				} else {
					return time;
				}
			},
			//判断是微信进入的还是支付宝进入的
			AlipayOrWxPay () {
				let UA = navigator.userAgent.toLowerCase();
				if (UA.match(/MicroMessenger/i) == "micromessenger") {
				  this.isWechat = true;
				} else if (UA.match(/alipayclient/i) == "alipayclient") {
				  this.isAlipay = true;
				}
			},
			noExistCode () {
				let query = {};
				let search = window.location.search.substring(1).split("&").forEach(item=>{
					let arr = item.split("=");
					query[arr[0]] = arr[1];
				});
				if (!query.code) {
					this.$msgbox({
						title : "提示",
						message : "需要对网页授权登录才能完成订单支付，请确定",
						showCancelButton : true,
					}).then(()=>{
						this.$store.commit("setLoading",true);
						let appId = "wxc2b279af443658f1";
						let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${encodeURIComponent(location.href)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
						window.open(url,"_self");
					})
					.catch(()=>{
						this.$message.error("取消授权将无法支付订单！");
					});
				}
			},
			getCode () {
				let query = {};
				let search = window.location.search.substring(1).split("&").forEach(item=>{
					let arr = item.split("=");
					query[arr[0]] = arr[1];
					this.query[arr[0]] = arr[1];
				});
				//如果是第二次支付则需要重新获取code
				if (this.$store.state.getCode) {
					this.$store.commit("setLoading",true);
					let appId = "wxc2b279af443658f1";
					let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${encodeURIComponent(location.href)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
					window.open(url,"_self");
				} else {
					this.getOrderInfo(JSON.parse(sessionStorage.getItem("OrderInfo")));
					sessionStorage.setItem("code",query.code);
				}
			},
			getOrderInfo (obj) {
				this.axios.post("/IceCardSelfHelp/GetIceOrderUpGradeInfo",obj).then(res=>{
					if (res.resStatusInfo.resultCode == "200") {
						this.orderInfo = res.orderInfo;
					} else {
						this.$message.error(res.resStatusInfo.errReason);
					}
				});
			},
			SelectPayType (type) {
				this.PayType = type;
			},
			wxPay () {
				console.log(this.query.code);
				if (!this.query.code) {
					this.noExistCode();
					return;
				}
				this.axios.post("/IceCardSelfHelp/GetWxJsApiParameters",{
					Code : sessionStorage.getItem("code"),//code
					TotalFee : this.orderInfo.AMOUNT,//金额
					Ndealid : this.orderInfo.NDEALID//订单号
				}).then(res=>{
					console.log(res);
					if (res.resStatusInfo.resultCode !== "200") {
						this.$message.warning(res.resStatusInfo.errReason);
						return;
					} else {
						WeixinJSBridge.invoke('getBrandWCPayRequest',{
						  appId : res.wechatparam.appId,
						  timeStamp: res.wechatparam.timeStamp,
						  nonceStr: res.wechatparam.nonceStr, // 支付签名随机串，不长于 32 位
						  package: res.wechatparam.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
						  signType: res.wechatparam.signType, // 微信支付V3的传入RSA,微信支付V2的传入格式与V2统一下单的签名格式保持一致
						  paySign: res.wechatparam.paySign// 支付签名
						},
						(res) => {
							sessionStorage.removeItem("code");
							this.$store.commit("getNewCode",true);
						    if (res.err_msg == "get_brand_wcpay_request:cancel") {
								this.getCode();
								this.$message.warning('取消支付');
						    } else if (res.err_msg == "get_brand_wcpay_request:fail") {
								this.getCode();
								this.$message.error('支付失败,请重试');
						    } else {
								this.$store.commit("setLoading",true);
								setTimeout(()=>{
									this.$store.commit("setLoading",false);
									this.$router.push({
										name : "PaySuccess"
									});
								},3000)
						    }
						});
					}
				});
			},
			zfbPay () {
				this.axios.post("/IceCardSelfHelp/GetAliPayParameters",{
					TotalFee : this.orderInfo.AMOUNT,//金额
					Ndealid : this.orderInfo.NDEALID,//订单号
					ProductName : this.cardInfo.STICKETNAMECH
				}).then(res=>{
					if (res) {
						const div = document.createElement('div')
						div.id = 'alipay'
						div.innerHTML = res;
						document.body.appendChild(div)
						document.querySelector('#alipay').children[0].submit() // 执行后会唤起支付宝
					} else {
						this.$message.error(res);
					}
				});
			},
			back () {
				this.$router.back();
			},
			Pay () {
				if (this.PayType == "wx") {
					this.wxPay();
				} else {
					this.zfbPay();
				}
			}
		}
	}
</script>

<style lang="scss" scoped="scoped">
	.page {
		padding: 10px;
	}
	::v-deep .el-card.box-card {
		margin-bottom: 22px;
	}
	.wxPay {
		margin-bottom: 9px;
	}
	.card {
		display: flex;
		padding: 14px;
		height: 53px;
		background: #FFFFFF;
		box-shadow: 0px 1px 3px 0px rgba(67, 67, 67, 0.1);
		border-radius: 9px;
		align-items: center;
		.left {
			flex: 2;
		}
	}
	.head-text {
		margin-bottom: 13px;
		font-size: 12px;
		color: #333;
	}
	.card-title {
		color: #333;
		font-weight: bold;
		font-size: 15px;
	}
	.timeOut {
		float: right;
		font-size: 14px;
		color: #E30204;
		font-weight: bold;
	}
	.waitPay {
		text-align: right;
		.text {
			font-size: 12px;
			font-weight: bold;
			color: #00306D;
			line-height: 62px;
		}
		.price {
			font-size: 18px;
			font-weight: bold;
			color: #E30204;
			line-height: 62px;
		}
	}
	.btn-list {
		display: flex;
		justify-content: center;
	}
	.btn-list button {
		border: none;
		width: 132px;
		height: 35px;
		font-size: 15px;
		font-weight: bold;
		line-height : 0px
	}
	.detail-Info {
		margin-right: 22px;
		background: url(../../assets/bluebg.png);
		background-size: 100% 100%;
		color: #FFEA00;
	}
	.btn-list .pay {
		background: url(../../assets/yellowbg.png);
		background-size: 100% 100%;
		color: #00306D;
	}
	.leftText {
		vertical-align: top;
		margin-left: 10px;
		font-size: 13px;
		font-weight: 400;
		color: #333333;
		line-height: 25px;
	}
	
</style>
<style>
	.el-message-box {
		width: 80% !important;
	}
</style>
